#include <iostream>
#include <pthread.h>
#include <vector>
#include <string>
#include <unistd.h>
#include"LockGuard.hpp"
using namespace std;
int NUM = 3;
int tickets = 1000;
pthread_mutex_t lock; // 锁
class threadDate
{
public:
    threadDate(int number)
    {
        _name = "thread_" + to_string(number);
    }

public:
    string _name;
};
void *getTicket(void *args)
{
    threadDate *date = static_cast<threadDate *>(args);
    // printf("i am %s\n",date->_name.c_str());
    while (1)
    {
        {
            //pthread_mutex_lock(date->lock_);
            LockGuard lockGuard(&lock);//区块加锁
            if (tickets > 0)
            {
                printf("%s get ticket %d\n", date->_name.c_str(), tickets);
                tickets--;
                //pthread_mutex_unlock(date->lock_);
            }
            else
            {
                //pthread_mutex_unlock(date->lock_);
                break;
            }
        }//离开区块解锁

        usleep(12);
    }
    printf("%s exit...\n", date->_name.c_str());
    return nullptr;
}
int main()
{
    vector<pthread_t> ids;
    vector<threadDate *> dates;
   
    pthread_mutex_init(&lock,nullptr);
    for (int i = 0; i < NUM; i++)
    {
        pthread_t id;
        threadDate *date = new threadDate(i /*, &lock*/);
        dates.push_back(date);
        pthread_create(&id, nullptr, &getTicket, date);
        ids.push_back(id);
    }
    for (auto id : ids)
    {
        pthread_join(id, nullptr);
    }
    pthread_mutex_destroy(&lock);
}
